package com.csea.tools.controller.miniapp;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.csea.tools.config.wechat.miniapp.WechatMiniappAccountConfig;
import com.csea.tools.config.wechat.miniapp.WechatMiniappConfiguration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Csea
 * @title
 * @date 2019/12/27 10:22
 */
@RestController
@RequestMapping("/miniapp")
@Api(description = "小程序接口")
@Slf4j
public class MiniappController {
    @Autowired
    private WechatMiniappAccountConfig accountConfig;
    @Autowired
    private WechatMiniappConfiguration miniappConfiguration;

    @ApiOperation(value = "获取openid",notes = "获取到openid，sessionKey，unionid")
    @ApiImplicitParam(name = "code", value = "进入小程序后获取到的code")
    @GetMapping("/login")
    public void login(String code) {
        if (StringUtils.isBlank(code)) {
            log.info("code为空");
        }
        log.info("appid ={}", accountConfig.getAppId());
        WxMaService wxMaService = miniappConfiguration.wxMaService();
        log.info("wxMaService= {}", wxMaService);
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            log.info("openid={}", session.getOpenid());
            log.info("sessionKey={}", session.getSessionKey());
        } catch (WxErrorException e) {
            log.info("error={}", e.getMessage());
            e.printStackTrace();
        }
    }
}
